﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace Ewts.ashx
{
    /// <summary>
    /// ProduceEntering 的摘要说明
    /// </summary>
    public class ProduceEntering : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            DataLib.BLL.Productions bll = new DataLib.BLL.Productions();

            string msg="-1";

            //if (context.Request["barid"] != null && context.Request["barid"].ToString().Trim() != "")
            //{
            //    //
               
            //}
            //else
            //{

                //如果第一次生成返还单号，G开头
                //插入记录
            DataLib.BLL.InStorage bllIn = new DataLib.BLL.InStorage();
           
            DataLib.BLL.ins_fuliao bllfl = new DataLib.BLL.ins_fuliao();
            DataLib.BLL.ins_sunhao bllsh = new DataLib.BLL.ins_sunhao();
            DataLib.BLL.sc_xh bllxh = new DataLib.BLL.sc_xh();
                DataLib.Model.InStorage insModel = new DataLib.Model.InStorage();
                int outid = 0;
                int insid = 0;
                int temp = 0;


                bool iresult = false;
                if (context.Request["hidOutID"] != null && context.Request["hidOutID"].ToString().Trim() != "0")
                {
                    outid = Convert.ToInt32(context.Request["hidOutID"]);
                }

                if (context.Request["hidInStoID"] != null && context.Request["hidInStoID"].ToString().Trim() != "0")
                {
                    insid = int.Parse(context.Request["hidInStoID"].ToString().Trim());
                }

                //操作类型
                string inputype = getObjTostring(context.Request["inputype"]);
                insModel = GetInstorage(insid, context);
                switch (inputype)
                {
                    case "nowstatus":
                        iresult = bll.GetConfirm(0, outid, insid, 1);
                        msg = Convert.ToInt32(iresult).ToString();
                        break;
                    case "xhinput":
                       // int goodsid = getNumberByobj(context.Request["barid"]);
                        decimal nwt = getDecimalByobj(context.Request["goodsxhnwt"]);
                        decimal qty = getDecimalByobj(context.Request["goodsxhqty"]);
                        string remark = context.Request["xhmemo"].ToString();
                        int xhid = getNumberByobj(context.Request["xhid"]);
                        //DataLib.BLL.sc_xh xhbll = new DataLib.BLL.sc_xh();
                        DataLib.Model.sc_xh xhmodel = bllxh.GetModel(xhid);
                        msg = "-1";
                        if (xhmodel != null)
                        { 
                            xhmodel.qty_xh = qty;
                            xhmodel.nwt_xh = nwt;
                            xhmodel.nwt_jy = xhmodel.nwt_src - nwt;
                            if (bllxh.Update(xhmodel))
                            {
                                msg = xhmodel.nwt_jy.ToString();
                            }
                            
                        }
                        break;
                    case "barcode"://返还
                        DataLib.Model.BarCode barMode = GetBarCode(context, insModel);
                        iresult = bll.GetFinshed(insid,outid);
                        if (iresult == true)
                            temp = 1;
                        else
                            temp = 0;
                        barMode.goodsname = insModel.wrlno;
                        barMode.remark = bll.GetStrFormulae((int)insModel.outid, "S") + "|"+ bll.GetStrFormulae((int)insModel.outid, "W");
                        msg = serializer.Serialize(barMode).Replace("}", ",\"iresult\":") + temp.ToString() + "}";
                        break;
                    case "fl"://辅料
                        DataLib.Model.ins_fuliao flModel = new DataLib.Model.ins_fuliao();
                        flModel = EditFL(context,insModel);
                        iresult = bll.GetFinshed(insid, outid);
                        if (iresult == true)
                            temp = 1;
                        else
                            temp = 0;
                        flModel.remark = bll.GetStrFormulae((int)insModel.outid, "S") + "|" + bll.GetStrFormulae((int)insModel.outid, "W");
                        msg = serializer.Serialize(flModel).Replace("}", ",\"iresult\":") + temp.ToString() + "}";
                        break;
                    case "sh"://损耗
                         DataLib.Model.ins_sunhao shModel = new DataLib.Model.ins_sunhao();
                        shModel = EditSh(context, insModel);
                        iresult = bll.GetFinshed(insid, outid);
                        if (iresult == true)
                            temp = 1;
                        else
                            temp = 0;
                        shModel.remark = bll.GetStrFormulae((int)insModel.outid, "S") + "|" + bll.GetStrFormulae((int)insModel.outid, "W");
                        msg = serializer.Serialize(shModel).Replace("}", ",\"iresult\":") + temp + "}";
                        break;
                    case "delhlid":     
                        //删除辅料
                         bllfl.Delete(int.Parse(context.Request["delhlid"].ToString().Trim()));
                         iresult = bll.GetFinshed(insid, outid);
                         if (iresult == true)
                             temp = 1;
                         else
                             temp = 0;
                         if (!IsReusable)
                         {
                             msg = bll.GetStrFormulae((int)insModel.outid, "S") + "|" + bll.GetStrFormulae((int)insModel.outid, "W");
                         }
                         else
                         {
                             msg = "0";
                         }
                         msg = temp.ToString() + msg;
                        break;
                    case "delshid":
                        //删除损耗
                       bllsh.Delete(int.Parse(context.Request["delshid"].ToString().Trim()));
                       iresult = bll.GetFinshed(insid, outid);
                        msg =Convert.ToInt32(iresult).ToString();
                        if (!IsReusable)
                        {
                            msg = bll.GetStrFormulae((int)insModel.outid, "S") + "|" + bll.GetStrFormulae((int)insModel.outid, "W");
                        }
                        else
                        {
                            msg = "0";
                        }
                        if (iresult == true)
                            temp = 1;
                        else
                            temp = 0;
                        msg = temp.ToString() + msg;
                        break;
                    case "delbarid":
                        //删除条码
                        msg = deleteByid(context.Request["delbarid"].ToString().Trim());
                        if (msg!="-1")
                        {
                            msg = bll.GetStrFormulae((int)insModel.outid, "S") + "|" + bll.GetStrFormulae((int)insModel.outid, "W");
                        }
                        else
                        {
                            msg = "0";
                        }
                        if (iresult == true)
                            temp = 1;
                        else
                            temp = 0;
                        msg = temp.ToString() + msg;
                        break;
                    case "GetXH":
                        //获取消耗
                        msg = GetJsonByXHid(int.Parse(context.Request["xhid"].ToString().Trim()));
                        break;
                   
                    case "UpdateXH":
                        //修改消耗
                        msg = UpdateXH(context);
                        break;
                    default:
                        break;
                }

               
            //}
            context.Response.Write(msg);
        }

        private DataLib.Model.InStorage GetInstorage(object obj, HttpContext context)
        {
            DataLib.Model.InStorage model = new DataLib.Model.InStorage();
            DataLib.BLL.InStorage bll = new DataLib.BLL.InStorage();
            //入库单操作，第一次就新增，否则读取传过来的入库单，绑定入库单号
            if (obj != null && obj.ToString().Trim() != "0")
            {
                model = bll.GetModel(int.Parse(obj.ToString()));
            }
            else
            {
                model = AddInStorage(context);
            }
            return model;
        }

        /// <summary>
        /// 添加 ins_fuliao 记录
        /// </summary>
        /// <param name="context"></param>
        public DataLib.Model.ins_fuliao EditFL(HttpContext context, DataLib.Model.InStorage insModel)
        {
            DataLib.BLL.Productions pbll = new DataLib.BLL.Productions();
            DataLib.Model.ins_fuliao flModel = new DataLib.Model.ins_fuliao();
            flModel.goodscode = getObjTostring(context.Request["gcode_fl"]);
            flModel.goodsname = getObjTostring(context.Request["gname_fl"]);
            flModel.gwt = decimal.Parse(context.Request["gwt_fl"]);
            flModel.nwt = decimal.Parse(getObjTostring(context.Request["nwt_fl"]));
            flModel.qty = int.Parse(getObjTostring(context.Request["qty_fl"]));
            flModel.remark = getObjTostring(context.Request["remark_fl"]);
            flModel.instroageid = (int)insModel.id;
            flModel.wrlno = insModel.wrlno;
            flModel.id = getNumberByobj(context.Request["flid"].ToString());
            flModel.tabno = pbll.GetFSNoint((int)insModel.id,'J');
            if (flModel.id == 0)
            {
                flModel.id = new DataLib.BLL.ins_fuliao().Add(flModel);
            }
            else
            {
                new DataLib.BLL.ins_fuliao().Update(flModel);
            }
            return flModel;
        }

        /// <summary>
        /// 添加 ins_sunhao 记录
        /// </summary>
        /// <param name="context"></param>
        public DataLib.Model.ins_sunhao EditSh(HttpContext context,DataLib.Model.InStorage insModel)
        {
            DataLib.Model.ins_sunhao shModel = new DataLib.Model.ins_sunhao();
            DataLib.BLL.Productions pbll = new DataLib.BLL.Productions();
            shModel.goodscode = getObjTostring(context.Request["gcode_sh"]);
            shModel.goodsname = getObjTostring(context.Request["gname_sh"]);
            shModel.gwt = decimal.Parse(context.Request["gwt_sh"]);
            shModel.nwt = decimal.Parse(getObjTostring(context.Request["nwt_sh"]));
            shModel.qty = int.Parse(getObjTostring(context.Request["qty_sh"]));
            shModel.remark = getObjTostring(context.Request["remark_sh"]);
            shModel.instroageid = (int)insModel.id;
            shModel.wrlno = insModel.wrlno;
            shModel.id = getNumberByobj(context.Request["shid"].ToString());
            shModel.tabno = pbll.GetFSNoint((int)insModel.id, 'H');

            //if (new DataLib.BLL.InStorage().GetConfirm((decimal)flModel.nwt, flModel.instroageid, 3) == false)
            //    return null;
            DataLib.BLL.ins_sunhao bll = new DataLib.BLL.ins_sunhao();
            if (shModel.id == 0)
            {
                shModel.id = bll.Add(shModel);
            }
            else
            {
                bll.Update(shModel);
            }
            return shModel;
        }

        /// <summary>
        /// 添加barcode并返回barcode的实体对象
        /// </summary>
        /// <param name="context"></param>
        /// <param name="inModel"></param>
        /// <returns></returns>
        public DataLib.Model.BarCode GetBarCode(HttpContext context, DataLib.Model.InStorage insModel)
        {
            string loadnum = "";
            int loadnumid = 0;
            if (context.Request["loadnum"] != null && context.Request["loadnum"].Trim() != "")
            {
                loadnum = getObjTostring(context.Request["loadnum"]);
                DataLib.Model.LoadNum loadmodel = new DataLib.BLL.LoadNum().GetLoadID(loadnum);
                if (loadmodel != null && loadmodel.id > 0)
                    loadnumid = (int)loadmodel.id;
            }

            string strtemp = null;
            DataLib.Model.BarCode bmodel = new DataLib.Model.BarCode();
            bmodel.cjoid = int.Parse(getObjTostring(context.Request["cjoid"], "0"));
            if (loadnumid > 0)
                bmodel.loadnumid = loadnumid;
            else
                bmodel.loadnumid = 0;

            bmodel.comeunder = getObjTostring(context.Request["comeunder"], "");
            bmodel.nwt = decimal.Parse(getObjTostring(context.Request["nwt"], "0"));
            bmodel.gwt = decimal.Parse(getObjTostring(context.Request["gwt"], "0")); ;
            bmodel.tare1 = 0;
            bmodel.tare2 = 0;
            bmodel.barbelong = context.Request["inDepart"];      //归属地
            bmodel.bargraphic = context.Request["outDepart"];     //处理地
            bmodel.qty = int.Parse(getObjTostring(context.Request["qty"], "0"));
            strtemp = getObjTostring(context.Request["islocak"]);
            if (strtemp != "")
                bmodel.isLocak = true;
            else
                bmodel.isLocak = false;

            bmodel.ParmentID = int.Parse(getObjTostring(context.Request["hidOutID"], "0"));
            bmodel.storageid = int.Parse(getObjTostring(context.Request["storageid"], "0"));
            bmodel.stroageNo = getObjTostring(context.Request["storageno"], "");
            bmodel.packageno = getObjTostring(context.Request["packageno"], "");
            bmodel.rdh = getObjTostring(context.Request["rdh"], "");
            bmodel.storageid = int.Parse(getObjTostring(context.Request["storageid"], "0"));
            bmodel.stroageNo = getObjTostring(context.Request["storageno"]);
            bmodel.remark = getObjTostring(context.Request["remark"]);
                bmodel.InStrorageID = (int)insModel.id;

           // bmodel.InStrorageID = getNumberByobj(context.Request["hidInStoID"]);
           // bmodel.OutStrorageID = getNumberByobj(context.Request["hidOutID"]);
            bmodel.status = -1;   //barcode  status
            bmodel.goodsid = getNumberByobj(context.Request["goodsid"]);
            bmodel.goodscode = getObjTostring(context.Request["goodscode"]);
            bmodel.goodsname = getObjTostring(context.Request["goodsname"]);
            bmodel.rubbishcode = getObjTostring(context.Request["rcode"]);
            bmodel.rubbishtype = getObjTostring(context.Request["rname"]);
            bmodel.plateid = getNumberByobj(context.Request["plateid"]);
            bmodel.plateno = getObjTostring(context.Request["plateno"]);
            bmodel.boxcount = getNumberByobj(context.Request["boxamount"]);
            bmodel.loadnumv = loadnum;


            if (context.Request["barcode"] != null && context.Request["barcode"].Trim() != "")
            {
                bmodel.barcodevalue = context.Request["barcode"].Trim();
            }
            else
            {
                string outson = getObjTostring(context.Request["outsno"]);
                bmodel.barcodevalue = Code.NumGeneration.GetSerialNum(bmodel.loadnumv + insModel.wrlno + bmodel.goodscode.PadRight(10, '0'), "BarCode");
            }


            bmodel.id = new DataLib.BLL.BarCode().Add(bmodel);
            return bmodel;

        }




        /// <summary>
        /// 当对象为空返回 "" 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string getObjTostring(object obj)
        {
            if (obj != null && obj.ToString().Trim() != "")
                return obj.ToString().Trim();
            else
                return "";
        }

        /// <summary>
        /// 当字符串为空 返回默认的值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public string getObjTostring(object obj, string def)
        {
            string str = getObjTostring(obj);
            if (str == "")
                str = def;
            return str;
        }
        public int getNumberByobj(object obj)
        {
            if (obj != null && obj.ToString().Trim() != "")
                return int.Parse(obj.ToString());
            else
                return 0;
        }
        public decimal getDecimalByobj(object obj)
        {
            if (obj != null && obj.ToString().Trim() != "")
                return Convert.ToDecimal(obj.ToString());
            else
                return 0;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

     
        /// <summary>
        /// 重量是否相等
        /// </summary>
        /// <param name="outid">出库生产ID</param>
        /// <param name="instroingid">生产返还单ID</param>
        /// <param name="nwt">新增加的重量</param>
        /// <param name="type">1为辅料 2为损耗 3为barcode</param>
        /// <returns>相等为true 可提交</returns>
        public bool IsWeightEqual(int outid, int instroingid, decimal nwt, int type)
        {
            bool iresult = false;

            //生产返还
            DataTable dtbarcode = new DataTable();
            DataLib.BLL.BarCode barbll = new DataLib.BLL.BarCode();
            dtbarcode = barbll.GetList(" status = -1 and ParmentID = " + outid).Tables[0];

            decimal totalbarcode = 0;
            for (int i = 0; i < dtbarcode.Rows.Count; i++)
            {
                //生产返还重重量
                totalbarcode += Convert.ToDecimal(dtbarcode.Rows[i]["gwt"]) * Convert.ToInt32(dtbarcode.Rows[i]["qty"]);
            }

            //生产辅料
            DataTable dtfl = new DataLib.BLL.ins_fuliao().GetList("instroageid=" + instroingid).Tables[0];
            decimal totalfl = 0;
            for (int i = 0; i < dtfl.Rows.Count; i++)
            {
                totalfl += Convert.ToDecimal(dtfl.Rows[i]["gwt"]) * Convert.ToInt32(dtfl.Rows[i]["qty"]);
            }

            //损耗
            DataTable dtsh = new DataLib.BLL.ins_sunhao().GetList("instroageid=" + instroingid.ToString().Trim()).Tables[0];
            decimal totalsh = 0;
            for (int i = 0; i < dtsh.Rows.Count; i++)
            {
                totalsh += Convert.ToDecimal(dtsh.Rows[i]["gwt"]) * Convert.ToInt32(dtsh.Rows[i]["qty"]);
            }
            List<DataLib.Model.BarCode> list = barbll.GetModelList(" status =21 and ParmentID = " + outid);
            decimal totalsrc = 0;
            for (int i = 0; i < list.Count; i++)
            {
                totalsrc += Convert.ToDecimal(list[i].gwt * list[i].qty);
            }

            if ((totalbarcode + totalfl) == (totalsh + totalsrc))
                iresult = true;

            return iresult;
        }
        /// <summary>
        /// 添加新的入库单
        /// </summary>
        public DataLib.Model.InStorage AddInStorage(HttpContext context)
        {
            DataLib.Model.InStorage inModel = new DataLib.Model.InStorage();
            DataLib.BLL.InStorage bll = new DataLib.BLL.InStorage();

            if (context.Request["oper"] != null)
            {
                inModel.Operator = context.Request["oper"].Trim();
            }
            if (context.Request["islocak"] != null && context.Request["islocak"].Trim() != "")
            {
                inModel.islock = Boolean.Parse(context.Request["islocak"]);
            }
            if (context.Request["inDepart"] != null && context.Request["inDepart"].Trim() != "")
            {
                inModel.InDepart = context.Request["inDepart"].Trim();
            }
            if (context.Request["outDepart"] != null && context.Request["outDepart"].Trim() != "")
            {
                inModel.OutDepart = context.Request["outDepart"].Trim();
            }
            if (context.Request["month"] != null && context.Request["month"].Trim().Length == 6)
            {
                inModel.clearingmonth = context.Request["month"].Trim();
            }
            else 
            {
                inModel.clearingmonth = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2,'0');
            }
            inModel.instoragetime = DateTime.Now;
            inModel.status = 7;    //生产录入中
            inModel.mechanerr = 0;
            inModel.cjoid = int.Parse(getObjTostring(context.Request["cjoid"], "0"));
            inModel.vloadnum = getObjTostring(context.Request["loadnum"], "0");
            if (context.Request["hidOutID"] != null && context.Request["hidOutID"].Trim() != "0")
            {
                inModel.outid = int.Parse(context.Request["hidOutID"].Trim());
                inModel.outno = inModel.outid.ToString();
            }

            string wrlno = "";
            wrlno = Code.NumGeneration.GetSerialNum("RS", "InCode");
            inModel.wrlno = wrlno;

            inModel.id = bll.Add(inModel);
            return inModel;

        }


        //根据id修改称重的信息
        protected string deleteByid(string id)
        {
            string result = "";

            DataLib.BLL.BarCode bll = new DataLib.BLL.BarCode();
            //barcode
            DataLib.Model.BarCode barcodeModel =bll.GetModel(Convert.ToInt32(id));
            if (barcodeModel.status == -1)
            {
                bll.Delete(Convert.ToInt32(id));
                result = "1";
            }
            else
            {
                result = "-1";
            }
            return result;
        }

        public string GetJsonByBarid(int barid)
        {
            string strjson = "";
            DataLib.Model.BarCode bar = new DataLib.BLL.BarCode().GetModel(barid);
            if (bar != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                strjson = serializer.Serialize(bar);
            }
            return strjson;

        }


        public string GetJsonByFLid(int flid)
        {
            string strjson = "";
            DataLib.Model.ins_fuliao model = new DataLib.BLL.ins_fuliao().GetModel(flid);
            if (model != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                strjson = serializer.Serialize(model);
            }
            return strjson;
        }

        public string GetJsonBySHid(int shid)
        {
            string strjson = "";
            DataLib.Model.ins_sunhao model = new DataLib.BLL.ins_sunhao().GetModel(shid);
            if (model != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                strjson = serializer.Serialize(model);
            }
            return strjson;
        }


        public string GetJsonByXHid(int xhid)
        {
            string strjson = "";
            DataLib.Model.sc_xh model = new DataLib.BLL.sc_xh().GetModel(xhid);
            if (model != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                strjson = serializer.Serialize(model);
            }
            return strjson;
        }

        public string UpdateFL(HttpContext context)
        {
            string flag = "-1";
            DataLib.BLL.ins_sunhao bll = new DataLib.BLL.ins_sunhao();
            DataLib.Model.ins_sunhao model = new DataLib.Model.ins_sunhao();
            bll.Update(model);
            return flag;
            
        }


        public string UpdateSH(HttpContext context)
        {
            string flag = "-1";

            DataLib.BLL.ins_sunhao bll = new DataLib.BLL.ins_sunhao();
            DataLib.Model.ins_sunhao model = new DataLib.Model.ins_sunhao();
            bll.Update(model);
            return flag;

        }

        public string UpdateXH(HttpContext context)
        {
            string flag = "-1";
            DataLib.BLL.ins_sunhao bll = new DataLib.BLL.ins_sunhao();
            DataLib.Model.ins_sunhao model = new DataLib.Model.ins_sunhao();
            bll.Update(model);
            return flag;

        }

    }


}